<template>
  <div>
    <div>
      <el-row>
        <el-col :span=20 :offset="2" style="margin-bottom: 30px">

          <el-menu mode="horizontal">
            <el-menu-item>
              <el-button @click="chooseClassVisible=true">选择管理的教学班</el-button>
            </el-menu-item>
            <el-menu-item v-if="isCoursewareListReady">
              已选择的教学班 : {{
                chosenClass.course_name + ' ' +
                chosenClass.year + ' ' +
                chosenClass.semester + ' ' +
                chosenClass.schedule
              }}
            </el-menu-item>
          </el-menu>

        </el-col>

        <el-col :span="22" :offset="1" v-if="isCoursewareListReady">

          <el-tabs v-model="chosenOp" tab-position="right" @tab-click="switchTabs">
            <el-tab-pane label="查看与更新课件" name="查看与更新课件">
              <el-table
                stripe
                :data="coursewareList"
                style="width: 100%">
                <el-table-column type="expand" fixed="left">
                  <template slot-scope="props">

                    <el-form label-position="left">
                      <el-form-item label="文件：" v-if="props.row.fileName!==null">
                        <span>
                          <el-button type="success" @click="dlFile(props.$index,props.row)">
                            {{ props.row.fileName }}
                          </el-button>
                        </span>
                      </el-form-item>
                      <el-form-item label="课件信息：">
                        <span>{{ props.row.coursewareDescription }}</span>
                      </el-form-item>

                    </el-form>


                  </template>
                </el-table-column>
                <el-table-column prop="coursewareName" sortable label="课件名称" width="150">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" content="展开行以查看详情" placement="top-start">
                      <b>
                        {{ scope.row.coursewareName }}
                      </b>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="课件权限">
                  <template slot-scope="scope">
                    {{ $global.mapDownloadPermission(scope.row.downloadPermission) }}
                  </template>
                </el-table-column>
                <el-table-column label="有效日期">
                  <template slot-scope="scope">
                    <div style="margin: 5px">
                      <el-tag size="mini" type="success">起</el-tag>
                      {{ $global.formatTimeString(scope.row.startTime) }}
                    </div>
                    <div style="margin: 5px">
                      <el-tag size="mini" type="danger">止</el-tag>
                      {{ $global.formatTimeString(scope.row.endTime) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="220">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="editCourseware(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="delCourseware(scope.$index, scope.row)">删除
                    </el-button>

                  </template>
                </el-table-column>

              </el-table>

            </el-tab-pane>


            <el-tab-pane label="添加课件" name="添加课件">
              <el-form ref="coursewareForm" :model="coursewareForm" label-position="top" label-width="80px">
                <el-form-item label="课件名称" required prop="coursewareName">
                  <el-input clearable v-model="coursewareForm.coursewareName" placeholder="请输入课件名称"></el-input>
                </el-form-item>
                <el-form-item label="课件权限" required prop="downloadPermission">
                  <el-select v-model="coursewareForm.downloadPermission" placeholder="请选择课件权限">
                    <!-- 对应了3种类型 -->
                    <el-option label="可下载并可见" value="0"></el-option>
                    <el-option label="可见不可下载" value="1"></el-option>
                    <el-option label="学生不可见" value="2"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="开始日期时间" required prop="startTime">
                  <el-date-picker
                    v-model="coursewareForm.startTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="截止日期时间" required prop="endTime">
                  <el-date-picker
                    v-model="coursewareForm.endTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="选择上传文件" prop="file">
                  <el-upload
                    class="uploadCourseware"
                    ref="uploadCourseware"
                    :limit="1"
                    :auto-upload="false"
                    :on-change="handleChange"
                    drag
                    action="#"
                    :file-list="coursewareForm.fileList"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  </el-upload>
                  <!--                  <el-input type="file" ref="uploadCourseware" v-model="coursewareForm.file">-->
                  <!--                    上传文件-->
                  <!--                  </el-input>-->
                </el-form-item>
                <el-form-item label="课件描述" required prop="coursewareDescription">
                  <el-input v-model="coursewareForm.coursewareDescription" placeholder="请输入课件描述"
                            type="textarea" :rows="4"></el-input>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="submitCourseware(isUpdate)">
                    {{ isUpdate ? '更新课件 ':  '创建新课件' }}
                  </el-button>
                  <el-button @click="resetCourseware">
                    {{ isUpdate ? '更改模式为创建新课件' : '重置内容' }}
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

          </el-tabs>
        </el-col>
      </el-row>
    </div>
    <div class="dialogSection">
      <el-dialog
        title="选择管理的教学班"
        :visible.sync="chooseClassVisible"
        width="30%"
        center
        destroy-on-close
      >
        <el-select v-model="chosenClass" placeholder="请选择要管理的课程" @change="handleClassChange">
          <el-option
            v-for="item in classes"
            :key="item.course_name"
            :label="item.course_name+' '+item.year+' '+item.semester+' '+item.schedule"
            :value="item">
          </el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelChoose">取 消</el-button>
<!--          <el-button type="primary" @click="confirmChooseClass">确 定</el-button>-->
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import tc from "../../store/teacher";
import axios from 'axios'
import qs from 'qs'

export default {
  computed: {
    classes() {
      return tc.getters.getClasses
    },

  },
  data() {
    return {
      isCoursewareListReady: false,
      chooseClassVisible: false,
      chosenClass: null,
      chosenOp: '查看与更新课件',
      isUpdate: false,
      coursewareList: [
        // {
        //   courseId: 0, coursewareId: 0,
        //   coursewareName: '课件1', downloadPermission: 0, coursewareDescription: '这里是文件描述',
        //   startTime: '1', endTime: '2',
        //   fileName: '',
        // },

      ],

      coursewareForm: {
        courseId: -1,
        coursewareId: -1,
        coursewareName: '',
        downloadPermission: 1,
        startTime: null, endTime: null,
        coursewareDescription: "",
        fileName: "",
        fileList: [],
        file: null,
      }

    }
  },
  methods: {
    editCourseware(index, row) {

      this.coursewareForm = row
      this.coursewareForm.downloadPermission = this.$global.mapDownloadPermission(this.coursewareForm.downloadPermission)
      this.chosenOp = '添加课件'
      this.isUpdate = true
    },
    delCourseware(index, row) {
      console.log(index, row);
      axios.post('/api/deleteCourseware', qs.stringify({courseId: row.courseId, coursewareId: row.coursewareId}))
        .then(res1 => {
          console.log(res1)
          this.coursewareList.splice(index,1)
          this.$message.success('删除成功')
        })

    },
    dlFile(index, row) {
      this.$message.info('文件正在下载，请稍候')
      this.$global.downloadCoursewareFile(row.courseId, row.coursewareId, row.fileName)
    },
    handleClassChange: function (chosen) {
      axios.post('/api/showAllCoursewares', qs.stringify({courseId: chosen.courseId})).then(res1 => {

        this.isCoursewareListReady = true
        console.log(this.chosenClass)
        this.chooseClassVisible = false
        this.coursewareList = res1.data.coursewareList
        console.log(this.coursewareList)
      })
    },
    switchTabs(tab, event) {
      console.log(this.coursewareList)
      if (!this.isUpdate) {
        this.$refs['coursewareForm'].resetFields();
      }
    },

    /**
     * 要做2件事，上传表单和上传文件
     *
     */
    submitCourseware(isUpdate) {
      console.log(this.coursewareForm)
      this.$refs['coursewareForm'].validate(valid => {
        if (valid) {
          if (isUpdate) {// 更新课件
            this.coursewareForm.startTime = Date(Date.parse(this.coursewareForm.startTime)).toString()
            this.coursewareForm.endTime = Date(Date.parse(this.coursewareForm.endTime)).toString()
            console.log('更新前检查', this.coursewareForm)
            axios.post('/api/modifyCourseware', qs.stringify(this.coursewareForm)).then(res1 => {
              console.log(res1)
              var formData = new window.FormData()
              formData.append('file', this.coursewareForm.file)
              formData.append('courseId', this.coursewareForm.courseId)
              formData.append('coursewareId', this.coursewareForm.coursewareId)// 复制coursewareId
              axios({  // 设置axios的参数
                url: '/api/uploadCoursewareFile',
                data: formData,
                method: 'post',
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }).then(res2 => {
                console.log('res2', res2)
                this.coursewareForm = {}
                this.$message.success(res1.data.message)
              }).catch(err2 => {
                console.log('err2', err2)
              })
            })
          } else {// 创建课件
            this.coursewareForm.courseId = this.chosenClass.courseId
            this.coursewareForm.startTime = this.coursewareForm.startTime.toString()
            this.coursewareForm.endTime = this.coursewareForm.endTime.toString()
            axios.post('/api/createCourseware', qs.stringify(this.coursewareForm)).then(res1 => {
              console.log(res1, 'res1')
              var formData = new window.FormData()
              formData.append('file', this.coursewareForm.file)
              formData.append('courseId', this.coursewareForm.courseId)
              formData.append('coursewareId', res1.data.coursewareId)// 复制coursewareId
              this.coursewareForm.coursewareId = res1.data.coursewareId

              axios({  // 设置axios的参数
                url: '/api/uploadCoursewareFile',
                data: formData,
                method: 'post',
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }).then(res2 => {
                console.log('res2', res2)
                this.coursewareList.push(this.coursewareForm)
                this.coursewareForm = {}
                this.$message.success('创建课件成功')
              }).catch(err2 => {
                console.log('err2', err2)
              })
            }).catch(err1 => {
              console.log(err1, 'err1')
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },


    resetCourseware() {
      if (this.isUpdate) {
        this.coursewareForm = {}
        this.isUpdate = false
      } else {
        this.$refs['coursewareForm'].resetFields();
      }
    },

    /**
     * 将体现在上传选择器中的内容赋值给表单
     * @param file
     * @param fileList
     */
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.coursewareForm.file = file.raw
        this.coursewareForm.fileName = fileList[0].name
      }
      console.log('file', fileList, file, this.coursewareForm.file)
    },
    confirmChooseClass() {


    },
    cancelChoose() {
      this.chooseClassVisible = false
    },

  },
  watch: {
    // coursewareForm: {
    //   deep: true,
    //   handler(newForm, oldForm) {
    //     console.log(newForm, oldForm)
    //   }
    // }
  }
}
</script>

<style scoped>

</style>
